package com.ibangnuo.manage.controller.fileUpload;

import com.ibangnuo.api.fileUpload.FileControllerApi;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.manage.service.wxpay.WxMerchantsIntoPiecesService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: wwy
 * @Date: 2019-12-30 10:21
 */
@Controller
public class FileController implements FileControllerApi {

    private static Logger LOGGER = LoggerFactory.getLogger(FileController.class);
    @Value("${file.uploadLocal}")
    private String uploadLocation;

    @Value("${file.webPath}")
    private String webPath;

    @Value("${file.local}")
    private String local;
    @Autowired
    private WxMerchantsIntoPiecesService wxMerchantsIntoPiecesService;
    /**
     * 上传图片
     * 1.获取上传图片
     * 2.获取上传地址
     * 3.生成图片名称
     * 4.保存到磁盘
     * 5.返回web资源地址
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/img")
    @ResponseBody
    public ObjectResult uploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        int indexOf = fileName.lastIndexOf(".");
        String fileType = fileName.substring(indexOf);
        String contentType = file.getContentType();
        try {
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            String imageFilePath = uploadLocation + uuid + fileType;
            File file1 = new File(imageFilePath);
            file.transferTo(file1);
            String webLoacl = webPath + uuid + fileType;
            Map<String, Object> map = new HashMap<>();
            map.put("webPath", webLoacl);
            return new ObjectResult(CommonCode.SUCCESS, map);
        } catch (IOException e) {
            LOGGER.error("图片上传获取流错误", e.getMessage());
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 上传图片新版
     * 1.获取上传图片
     * 2.获取上传地址
     * 3.生成图片名称
     * 4.保存到磁盘
     * 5.返回web资源地址
     * @param file
     * @return
     */
    @PostMapping("/upload/img2/{imgName}")
    @ResponseBody
    public ObjectResult uploadFileNew(MultipartFile file, @PathVariable("imgName") String imgName) {
        String fileName = file.getOriginalFilename();
        int indexOf = fileName.lastIndexOf(".");
        String fileType = fileName.substring(indexOf);
        String contentType = file.getContentType();
        try {
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            String imageFilePath = uploadLocation + uuid + fileType;
            File file1 = new File(imageFilePath);
            file.transferTo(file1);
            String webLoacl = webPath + uuid + fileType;
            Map<String, Object> map = new HashMap<>();
            map.put("webPath", webLoacl);
            map.put("name", imgName);
            return new ObjectResult(CommonCode.SUCCESS, map);
        } catch (IOException e) {
            LOGGER.error("图片上传获取流错误", e.getMessage());
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 上传图片新版
     * 1.获取上传图片
     * 2.获取上传地址
     * 3.生成图片名称
     * 4.保存到磁盘
     * 5.返回web资源地址
     *
     * @param
     * @return
     */
    @PostMapping("/upload/image/{name}")
    @ResponseBody
    public ObjectResult save(@RequestParam("imgFile") MultipartFile imgFile, @PathVariable("name") String imageName) throws IOException {
        try {
            String filename = imgFile.getOriginalFilename();//得到原始文件的名称
            //得到文件的 后缀
            String lastName = filename.substring(filename.indexOf("."));
            //生成一个当前的时间来作为文件的名字
            SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd");//设置日期格式
            String time = UUID.randomUUID().toString().replace("-","");// new Date()为获取当前系统时间
            //生成一个新的名字
            String realName = time + lastName;
            Map<String, Object> map = new HashMap<>();
            map.put("imgName", realName);
            //将图片保存到指定的路径
            if ("businessLicense".equals(imageName)) {//营业执照
                imgFile.transferTo(new File(local + realName));
                map.put("path", local + realName);
                return new ObjectResult(CommonCode.SUCCESS, map);
            } else if ("qualificationLicense".equals(imageName)) {//资质许可证
                imgFile.transferTo(new File(local + realName));
                map.put("path", local + realName);
                return new ObjectResult(CommonCode.SUCCESS, map);
            } else if ("shopPhotos".equals(imageName)) {//门店特色照片
                imgFile.transferTo(new File(local + realName));
                map.put("path", local + realName);
                return new ObjectResult(CommonCode.SUCCESS, map);
            }
        } catch (IOException e) {
            LOGGER.error("图片上传获取流错误", e.getMessage());
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 微信上传图片
     * @param file
     * @param imgName
     * @return
     */
    @PostMapping("/upload/img3/{imgName}")
    @ResponseBody
    public ObjectResult uploadImgFileWx(MultipartFile file,@PathVariable("imgName") String imgName){
        String fileName = file.getOriginalFilename();
        int indexOf = fileName.lastIndexOf(".");
        String fileType = fileName.substring(indexOf);
        String contentType = file.getContentType();
        try {
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            String imageFilePath = uploadLocation+uuid+fileType;
            File file1 = new File(imageFilePath);
            file.transferTo(file1);
            String webLoacl = webPath+uuid+fileType;
            Map<String,Object> map = new HashMap<>();
            map.put("webPath",webLoacl);
            map.put("name",imgName);
            Map<String, String> map1 = wxMerchantsIntoPiecesService.uploadImg(file);
            map.putAll(map1);
            return new ObjectResult(CommonCode.SUCCESS,map);
        } catch (IOException e) {
            LOGGER.error("图片上传获取流错误",e.getMessage());
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }
}
